<?php

namespace app\admin\controller\mall;

use app\api\model\mysql\MallAccountLog;
use app\api\model\mysql\MallOrder;
use app\api\model\mysql\MallOrderGoods;
use app\api\model\mysql\MallUser;
use app\common\controller\AdminController;
use app\common\lib\ArrClass;
use app\common\lib\Str;
use app\common\model\MallCommissionLevel;
use think\App;

class Fxorder extends AdminController
{
    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallOrder();
    }

    public function index(){
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames3();

            $count = $this->model
                ->where($where)
                ->whereOr([['commission','>',0]])
                ->whereOr([['againprice','>',0]])
                ->count();
            $list = $this->model
                ->where($where)
                ->whereOr([['commission','>',0]])
                ->whereOr([['againprice','>',0]])
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            foreach($list as $k=>$v){
                $user =(new MallUser())->alias('u')->field('u.*,m.nickName as fromnickName')->join('mall_user m','m.id=u.parent_id')->where("u.openid='".$v['openid']."'")->find();
                $list[$k]['nickName'] =!empty($user) ? $user['nickName']:'';
                $list[$k]['fromnickName'] = !empty($user) ? $user['fromnickName']:'';
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    public function edit($id){
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            switch($post['orderToStatus']){
                case 1: //确认付款
                    $post['orderstatus'] =1;
                    $post['paytime'] =time();
                    break;
                case 2: //确认发货
                    if(!$post['express'] || !$post['expresscom'] || !$post['expresssn']){
                        $this->error('发货信息请填写完整');
                    }
                    $post['orderstatus'] =2;
                    $post['shipping_time'] =time();
                    break;
                case 3: //确认收货
                    $post['orderstatus'] =3;
                    $post['confirm_time'] =time();
                    break;
                case 4: //已完成

                    break;
                default:
                    break;
            }
            $this->model->startTrans();
            try {
                $save = $row->save($post);
                if($post['orderToStatus'] == 3){
                    $order =$this->model->find($id);
                    // 付款完成，返利以及分销商升级
                    $member = (new MallUser())->getUserByList($order['openid'],'id,openid,nickName,commission_level,parent_id');
                    $levels =(new MallCommissionLevel())->getLevels();
                    foreach ($levels as $k=>$v){
                        // 满足购买商品金额进行升级
                        if($v['ordermoney'] <= $order['payprice'] && $v['id']>$member['commission_level']){
                            (new MallUser())->where("id",$member['id'])->save(array('commission_level'=>$v['id']));
                        }
                    }
                    if($member['parent_id'] >0){
                        $parentmember = (new MallUser())->getUserById($member['parent_id'],'id,openid,nickName,commission_level');
                        $levelinfo =(new MallCommissionLevel())->getlevelInfo($parentmember['commission_level']);

                        $count=$this->model->getOrderByCount([['orderstatus','in',[3,4]],['openid','=',$member['openid']]]);
                        if($count==1){ //首单
                            //(new MallAccountLog())->saveAccoutLog($id,$parentmember['openid'],$levelinfo['commission_firstmoney'],3,'推荐返利');
                            (new MallAccountLog())->saveAccoutLog($id,$parentmember['openid'],$order['commission'],3,'推荐返利');
                        }

                        // 下级会员数满足条件 升级等级
                        $memcount =(new MallUser())->getMemCount($member['parent_id']);
                        if($levelinfo['membercount']<=$memcount && $levelinfo['membercount']>0 && $parentmember['commission_level']<5){
                            (new MallUser())->where("id",$member['parent_id'])->inc('commission_level',1)->update();
                            (new MallUser())->where("id",$member['parent_id'])->save(array('level_time'=>time()));
                        }
                    }
                }

            } catch (\Exception $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            $this->model->commit();
            $this->success('保存成功');
        }
        switch ($row['orderstatus']){
            case 0:
                $row['statusname'] ='待付款';
                break;
            case 1:
                $row['statusname'] ='待发货';
                break;
            case 2:
                $row['statusname'] ='待收货';
                break;
            case 3:
                $row['statusname'] ='已完成';
                break;
            case 4:
                $row['statusname'] ='售后/退款';
                break;
            default:
                $row['statusname'] ='已取消';
                break;
        }
        $userinfo =(new MallUser())->alias('u')->field('u.*,m.nickName as fromnickName')->join('mall_user m','m.id=u.parent_id')->where("u.openid='".$row['openid']."'")->find();
        $row['nickName'] =$userinfo['nickName'];
        $row['fromnickName'] =$userinfo['fromnickName'];
        $goodslist=(new MallOrderGoods())->getByOrderGoodsList($id);

        $this->assign('row', $row);
        $this->assign('goodslist', $goodslist);
        return $this->fetch();
    }
}